from .apps import ShopConfig

class DatabaseRouter:
    """
    A router to control all database operations on models in the
    shop application.
    """
    def db_for_read(self, model, **hints):
        """
        Attempts to read shop models go to shop_db.
        统计类查询路由到从库
        """
        if model._meta.app_label == 'shop':
            # 商品销量排行等统计类查询使用从库
            if hints.get('is_stat_query', False):
                return 'replica'
            return 'shop_db'
        return None

    def db_for_write(self, model, **hints):
        """
        Attempts to write shop models go to shop_db.
        """
        if model._meta.app_label == 'shop':
            return 'shop_db'
        return None

    def allow_relation(self, obj1, obj2, **hints):
        """
        Allow relations if a model in the shop app is involved.
        """
        if obj1._meta.app_label == 'shop' or \
           obj2._meta.app_label == 'shop':
            return True
        return None

    def allow_migrate(self, db, app_label, model_name=None, **hints):
        """
        Make sure the shop app only appears in the 'shop_db'
        database.
        """
        if app_label == 'shop':
            return db == 'shop_db'
        return None